﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AppLab.Models;
using AppLab.Web;
using AppLab.Web.Services;
using Wicresoft.AppFlow.Flows;
using AppLab.Controls;

namespace AppLab.Views
{
    public partial class Review : Page
    {
        private IList<OperationBase> possiblyPendingOperations = new List<OperationBase>();
        private FlowContext flow = new FlowContext();
        private ReviewSubmitData reviewSubmitData = new ReviewSubmitData();
        /// <summary>
        /// 控制每页DateGrid的行数
        /// </summary>
        private const int pageSize = 6;

        public Review()
        {
            InitializeComponent();
            PageScrollViewer.SetIsMouseWheelScrollingEnabled(true);
            this.Title = ApplicationStrings.ReviewPageTitle;
            this.DataContext = reviewSubmitData;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            busyIndicatorLoad.IsBusy = true;
            BindTesterAndPriority();
            BindGrid(0);
        }

        #region 分页处理，每次加载一页
        private void BindGrid(int pageIndex)
        {
            InvokeOperation<int> iCount = flow.GetReviewCount();
            iCount.Completed += new EventHandler(iCount_Completed);

            var query = flow.GetReviewDataGridQuery(pageSize, pageIndex);
            LoadOperation<ReviewSubmitData> loadOp = flow.Load(query);
            loadOp.Completed += new EventHandler(loadOp_Completed);
        }

        void loadOp_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOp = (LoadOperation)sender;
            dataGrid1.ItemsSource = loadOp.Entities;
            dataGrid1.SelectedIndex = 0;
            //当前页审核记录为空,调转上一页
            if (loadOp.TotalEntityCount <= 0)
            {
                if (dpReviewInfo.PageIndex > 0)
                {
                    dpReviewInfo.PageIndex = 0;
                    BindGrid(0);
                }
                else
                {
                    this.detailInfo.IsHitTestVisible = false;
                    this.TipsForAdaptation.Text = ApplicationStrings.TipsForNoNewReviewedAdaptation;
                }
            }
            else
            {
                this.detailInfo.IsHitTestVisible = true;
            }
            busyIndicatorLoad.IsBusy = false;
        }

        void iCount_Completed(object sender, EventArgs e)
        {
            InvokeOperation invokeOp = (InvokeOperation)sender;
            if (dpReviewInfo.PageIndex <= 0)
            {
                dpReviewInfo.BindSource((int)(invokeOp.Value), pageSize);
                dpReviewInfo.PageIndexChanged -= new EventHandler<EventArgs>(dpReviewInfo_PageIndexChanged);
                dpReviewInfo.PageIndexChanged += new EventHandler<EventArgs>(dpReviewInfo_PageIndexChanged);
            }
        }

        void dpReviewInfo_PageIndexChanged(object sender, EventArgs e)
        {
            BindGrid(dpReviewInfo.PageIndex);
        }

        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            InputValueClear();
            if (dataGrid1.SelectedItem != null)
            {
                //ReviewCustomDataForm form = new ReviewCustomDataForm();
                //form.CurrentItem = this.dataGrid1.SelectedItem;
                //form.CommandButtonsVisibility = DataFormCommandButtonsVisibility.None;
                //form.AutoEdit = true;

                //this.dataForm.CurrentItem = null;
                //dataForm.CommandButtonsVisibility = DataFormCommandButtonsVisibility.None;
                //dataForm.AutoEdit = true;
                //this.dataForm = form;

                //this.dataForm = new ReviewCustomDataForm();
                //this.dataForm.AutoEdit = true;
                //this.dataForm.CommandButtonsVisibility = DataForm.;
                this.dataForm.CurrentItem = this.dataGrid1.SelectedItem;

                //this.dataForm.CurrentItem =null;
                //this.dataForm.CurrentItem = this.dataGrid1.SelectedItem;


                this.dataForm.AutoGeneratingField -= new EventHandler<DataFormAutoGeneratingFieldEventArgs>(dataForm_AutoGeneratingField);

                //this.DataForm.CurrentItem = this.dataGrid1.SelectedItem;
               // this.dataForm.AutoGeneratingField -= new EventHandler<DataFormAutoGeneratingFieldEventArgs>(dataForm_AutoGeneratingField);
                this.TipsForAdaptation.Text = (dataGrid1.SelectedItem as ReviewSubmitData).MoblieBrandAndType + ApplicationStrings.TipsForAdaptationStr;
                //this.DataForm.AutoGeneratingField += new EventHandler<DataFormAutoGeneratingFieldEventArgs>(DataForm_AutoGeneratingField);
                this.dataForm.AutoGeneratingField += new EventHandler<DataFormAutoGeneratingFieldEventArgs>(dataForm_AutoGeneratingField);

            }
        }

        void dataForm_AutoGeneratingField(object sender, DataFormAutoGeneratingFieldEventArgs e)
        {
            // Put all the fields in adding mode
            e.Field.Mode = DataFieldMode.AddNew;
            ReviewSubmitData review = this.dataGrid1.SelectedItem as ReviewSubmitData;

            if (e.PropertyName == "SubmitUpgradePackage")
            {
                e.Field.ReplaceTextBox(new DownloadLink(review.FlowGuid, "SubmitUpgradePackage"), DownloadLink.ContentProperty, null);

            }
            else if (e.PropertyName == "SubmitReleaseNote")
            {

                e.Field.ReplaceTextBox(new DownloadLink(review.FlowGuid, "SubmitReleaseNote"), DownloadLink.ContentProperty, null);

            }
            else if (e.PropertyName == "SubmitSelfTest")
            {

                e.Field.ReplaceTextBox(new DownloadLink(review.FlowGuid, "SubmitSelfTest"), DownloadLink.ContentProperty, null);

            }
            else if (e.PropertyName == "SubmitAnythingElse")
            {

                e.Field.ReplaceTextBox(new DownloadLink(review.FlowGuid, "SubmitAnythingElse"), DownloadLink.ContentProperty, null);
            }
        }

        #endregion

        private void BindTesterAndPriority()
        {
            //绑定测试人员
            var query = flow.GetTesterQuery();
            var loadOp = flow.Load(query);
            cmbTesters.ItemsSource = loadOp.Entities;
            cmbTesters.DisplayMemberPath = "DisplayName";

            //绑定等级
            this.cmbPriority.Items.Add("1");
            this.cmbPriority.Items.Add("2");
            this.cmbPriority.Items.Add("3");
            this.cmbPriority.Items.Add("4");
        }

        // Executes when the user tries to leave this page.
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            foreach (OperationBase operation in this.possiblyPendingOperations)
            {
                if (!operation.IsComplete)
                {
                    if (operation.CanCancel)
                    {
                        operation.Cancel();
                    }
                    else
                    {
                        e.Cancel = true;
                    }
                }
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (!Verification()) return;

            ReviewSubmitData rsd = new ReviewSubmitData();
            ReviewSubmitData selItem = this.dataGrid1.SelectedItem as ReviewSubmitData;
            rsd.FlowGuid = (dataGrid1.SelectedItem as ReviewSubmitData).FlowGuid;
            rsd.ReviewResult = (bool)rdoAccept.IsChecked ? FlowState.PendingTest : FlowState.RejectByReviewer;
            rsd.ReviewBy = WebContext.Current.User.Name;
            rsd.IsAccept = (bool)rdoAccept.IsChecked;
            rsd.MediaClientID = (dataGrid1.SelectedItem as ReviewSubmitData).MediaClientID;
            rsd.ReviewTime = DateTime.Now;
            rsd.RowGuid = (dataGrid1.SelectedItem as ReviewSubmitData).RowGuid;
            if ((bool)rdoAccept.IsChecked)
            {
                rsd.AssignedTo = (cmbTesters.SelectedItem as Tester).Alias;
                rsd.Priority = int.Parse(cmbPriority.SelectedItem.ToString());
                rsd.TestTaskEAT = DateTime.Parse(dtpComplTime.Text);
                rsd.ReviewComment = string.Empty;
            }
            else
            {
                rsd.ReviewComment = txtReviewComment.Text;
                rsd.SubmitByAlias = selItem.SubmitByAlias;//Email 需要数据
            }
            //Emial需要的其他数据
            rsd.MobileBrand = selItem.MobileBrand;
            rsd.MobileType = selItem.MobileType;
            rsd.MobileVersion = selItem.MobileVersion;

            rsd.SubmitBy = selItem.SubmitBy;
            rsd.SubmitTime = selItem.SubmitTime;

            reviewSubmitData.CurrentOperation = this.flow.Review(rsd.FlowGuid, rsd, this.ReviewOperation_Completed, null);
            this.possiblyPendingOperations.Add(reviewSubmitData.CurrentOperation);
        }

        private void ReviewOperation_Completed(InvokeOperation<Guid> operation)
        {
            if (!operation.IsCanceled)
            {
                if (operation.HasError)
                {
                    ErrorWindow.CreateNew(operation.Error);
                    operation.MarkErrorAsHandled();
                }
                else if (operation.Value != Guid.Empty)
                {
                    MessageBox.Show(PopupDialogStrings.CompletedReview, this.Title, MessageBoxButton.OK);
                    busyIndicatorLoad.IsBusy = true;
                    InputValueClear();
                    BindGrid(dpReviewInfo.PageIndex);
                }
                else
                {
                    ErrorWindow.CreateNew(ErrorResources.ErrorWindowGenericError);
                }
            }
        }

        private bool Verification()
        {
            if (!WebContext.Current.User.IsAuthenticated)
            {
                this.TipsForWrongInfo.Text = PopupDialogStrings.MustBeLoggedInString;
                return false;
            }

            if (dataGrid1.SelectedItem == null)
            {
                this.TipsForWrongInfo.Text = PopupDialogStrings.SelectedAuditClientOnReview;
                return false;
            }

            if ((bool)this.rdoAccept.IsChecked && cmbTesters.SelectedItem == null)
            {
                this.TipsForWrongInfo.Text = PopupDialogStrings.SelectedReviewByName;
                return false;
            }

            if ((bool)rdoReject.IsChecked && (string.IsNullOrWhiteSpace(txtReviewComment.Text) || txtReviewComment.Text.Replace(" ", "").Equals(PopupDialogStrings.InputRejectedReason)))
            {
                this.TipsForWrongInfo.Text = PopupDialogStrings.InputRejectedReasonOnReview;
                return false;
            }

            if ((bool)this.rdoAccept.IsChecked && cmbPriority.SelectedItem == null)
            {
                this.TipsForWrongInfo.Text = PopupDialogStrings.SelectedPriorityOnReview;
                return false;
            }

            if ((bool)this.rdoAccept.IsChecked && string.IsNullOrEmpty(this.dtpComplTime.Text))
            {
                this.TipsForWrongInfo.Text = PopupDialogStrings.InputSpecifiedDataTimeOnReview;
                return false;
            }
            if ((bool)this.rdoAccept.IsChecked && !string.IsNullOrEmpty(this.dtpComplTime.Text) && DateTime.Compare(DateTime.Parse(this.dtpComplTime.Text), DateTime.Now.Date) < 0)
            {
                this.TipsForWrongInfo.Text = PopupDialogStrings.LessThanDataTimeOnReview + DateTime.Now.ToShortDateString() + "！";
                return false;
            }
            this.TipsForWrongInfo.Text = string.Empty;
            return true;
        }

        private void InputValueClear()
        {
            this.cmbTesters.SelectedItem = null;
            this.cmbPriority.SelectedItem = null;
            this.txtReviewComment.Text = string.Empty;
            this.dtpComplTime.Text = string.Empty;
            this.TipsForWrongInfo.Text = string.Empty;
            this.rdoAccept.IsChecked = true;
        }

        /// <summary>
        /// 是否拒绝
        /// </summary>
        private bool iReject = false;
        private void rdoReject_Checked(object sender, RoutedEventArgs e)
        {
            iReject = true;
            this.cmbTesters.SelectedItem = null;
            this.cmbPriority.SelectedItem = null;
            this.dtpComplTime.Text = string.Empty;
            this.TipsForWrongInfo.Text = string.Empty;
            this.txtReviewComment.Text = PopupDialogStrings.InputRejectedReason;
        }

        private void txtReviewComment_GotFocus(object sender, RoutedEventArgs e)
        {
            if (iReject)
            {
                this.txtReviewComment.Text = string.Empty;
            }
        }

        private void txtReviewComment_LostFocus(object sender, RoutedEventArgs e)
        {
            iReject = false;
        }

        private void rdoAccept_Checked(object sender, RoutedEventArgs e)
        {
            this.TipsForWrongInfo.Text = string.Empty;
        }

        //private void DataForm_AutoGeneratingField(object sender, DataFormAutoGeneratingFieldEventArgs e)
        //{
        //    // Put all the fields in adding mode
        //    e.Field.Mode = DataFieldMode.AddNew;
        //    ReviewSubmitData review = this.dataGrid1.SelectedItem as ReviewSubmitData;
        //    if (e.PropertyName == "MoblieBrandAndType")
        //    {
        //        e.Field.ReplaceTextBox(new TextBlock(), TextBlock.TextProperty, null);
        //    }
        //    else if (e.PropertyName == "SubmitBy")
        //    {
        //        e.Field.ReplaceTextBox(new TextBlock(), TextBlock.TextProperty, null);
        //    }
        //    else if (e.PropertyName == "SubmitTimeString")
        //    {
        //        e.Field.ReplaceTextBox(new TextBlock(), TextBlock.TextProperty, null);//bingding=>bingding.Converter = new DateTimeConverter());
        //    }
        //    else if (e.PropertyName == "SubmitType")
        //    {
        //        e.Field.ReplaceTextBox(new TextBlock(), TextBlock.TextProperty, null);
        //    }
        //    else if (e.PropertyName == "SubmitComment")
        //    {
        //        TextBlock txBlock = new TextBlock();
        //        txBlock.Width = 255;
        //        txBlock.TextWrapping = TextWrapping.Wrap;
        //        e.Field.ReplaceTextBox(txBlock, TextBlock.TextProperty, null);
        //    }
        //    else if (e.PropertyName == "SubmitPackage")
        //    {
        //        e.Field.ReplaceTextBox(new DownloadLink(review.FlowGuid, "SubmitPackage"), DownloadLink.ContentProperty, null);
        //    }
        //    else if (e.PropertyName == "SubmitUpgradePackage")
        //    {
        //        //if (GetEnableUpgradePackage())
        //        //{
        //        e.Field.ReplaceTextBox(new DownloadLink(review.FlowGuid, "SubmitUpgradePackage"), DownloadLink.ContentProperty, null);
        //        //}
        //        //else
        //        //{
        //        //e.Field.ReplaceTextBox(new TextBlock(), TextBlock.TextProperty, null);
        //        // }
        //    }
        //    else if (e.PropertyName == "SubmitReleaseNote")
        //    {
        //        //if (this.GetEnableSubmitReleaseNote())
        //        //{
        //        //    e.Field.ReplaceTextBox(new DownloadLink(review.FlowGuid, "SubmitReleaseNote"), DownloadLink.ContentProperty, null);
        //        //}
        //        //else
        //        //{
        //        e.Field.ReplaceTextBox(new TextBlock(), TextBlock.TextProperty, null);
        //        //}
        //    }
        //    else if (e.PropertyName == "SubmitSelfTest")
        //    {
        //        //if (GetEnableSubmitSelfTest())
        //        //{
        //        //    e.Field.ReplaceTextBox(new DownloadLink(review.FlowGuid, "SubmitSelfTest"), DownloadLink.ContentProperty, null);
        //        //}
        //        //else
        //        //{
        //        e.Field.ReplaceTextBox(new TextBlock(), TextBlock.TextProperty, null);
        //        // }
        //    }
        //    else if (e.PropertyName == "SubmitAnythingElse")
        //    {
        //        //if (GetEnableAnythingElse())
        //        //{
        //        //    e.Field.ReplaceTextBox(new DownloadLink(review.FlowGuid, "SubmitAnythingElse"), DownloadLink.ContentProperty, null);
        //        //}
        //        //else
        //        //{
        //        e.Field.ReplaceTextBox(new TextBlock(), TextBlock.TextProperty, null);
        //        // }
        //    }
        //    else if (e.PropertyName == "InspectionReport")
        //    {
        //        //if (GetEnableSpectionReport())
        //        //{
        //            e.Field.ReplaceTextBox(new DownloadLink(review.FlowGuid, "InspectionReport"), DownloadLink.ContentProperty, null);
        //        //}
        //        //else
        //        //{
        //        //    e.Field.ReplaceTextBox(new TextBlock(), TextBlock.TextProperty, null);
        //        //}
        //    }
        //}
    }
}
